import { ComponentInfoType, ComponentsStateType } from "./index";
export function getNextSelectedId(
  fe_id: string,
  componentList: ComponentInfoType[]
) {
  const visibleComponent = componentList.filter((c) => !c.isHidden);
  const index = visibleComponent.findIndex((c) => c.fe_id === fe_id);
  if (index < 0) return "";
  //重新计算 selectedId
  let newSelectedId = "";
  const length = visibleComponent.length;
  if (length <= 1) {
    //组件长度就一个 ，被删除了，就没有组件了
    newSelectedId = "";
  } else {
    if (index + 1 === length) {
      //删除最后一项，就要选中上一个
      newSelectedId = visibleComponent[index - 1].fe_id;
    } else {
      //删除不实最后一项，则选中下一个
      newSelectedId = visibleComponent[index + 1].fe_id;
    }
  }
  return newSelectedId;
}
/**
 *
 * @param draft  state draft
 * @param newComponent  新组件
 */
export function insertNewComponent(
  draft: ComponentsStateType,
  newComponent: ComponentInfoType
) {
  const { selectedId, componentList } = draft;
  const index = componentList.findIndex((c) => c.fe_id === selectedId);
  //未选中任何组件，
  if (index < 0) {
    draft.componentList.push(newComponent);
  } else {
    //选中了组件 插入到index 后面
    draft.componentList.splice(index + 1, 0, newComponent);
  }
  draft.selectedId = newComponent.fe_id;
}
